package com.blqy.fr.user.api.login;

import cn.hutool.crypto.digest.MD5;
import com.blqy.fr.account.client.UserBillFeignClient;
import com.blqy.fr.common.constant.RedisConstant;
import com.blqy.fr.common.execption.BlQyException;
import com.blqy.fr.common.result.Result;
import com.blqy.fr.common.result.ResultCodeEnum;
import com.blqy.fr.model.user.User;
import com.blqy.fr.user.login.LoginAccount;
import com.blqy.fr.user.login.LoginClient;
import com.blqy.fr.user.login.LoginType;
import com.blqy.fr.user.mapper.UserMapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.UUID;

@Tag(name = "账户登录接口")
@RestController
@Slf4j
@RequestMapping("/api/user/account")
public class AccountLoginApiController {



    @Autowired
    private LoginClient loginClient;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserBillFeignClient userBillFeignClient;


    @PostMapping("accountLogin")
    public Result<Map<String, Object>> accountLogin(@RequestBody LoginAccount loginAccount) throws Exception {
        return Result.ok(loginClient.login(LoginType.ACCOUNT_LOGIN.type, loginAccount));
    }


    @PostMapping("register")
    public Result register(@RequestBody LoginAccount loginAccount) throws Exception {
        if (StringUtils.isBlank(loginAccount.getUsername())){
            throw new BlQyException(ResultCodeEnum.ACCOUNT_ERROR);
        }else{
            if (!(loginAccount.getUsername().length()==11)){
                throw new BlQyException(ResultCodeEnum.ACCOUNT_ERROR);
            }
        }

        if (StringUtils.isBlank(loginAccount.getPassword())){
            throw new BlQyException(ResultCodeEnum.PASSWORD_ERROR);
        }else if (loginAccount.getPassword().length()<6){
            throw new BlQyException(ResultCodeEnum.PASSWORD_ERROR);
        }


        User user = new User();
        user.setAcconut(loginAccount.getUsername());
        String string = UUID.randomUUID().toString();
        String replace = string.replace("-", "").substring(0, 8);
        user.setUserName("用户"+ replace);
        user.setNickName("员工1" + redisTemplate.opsForValue().increment(RedisConstant.USER_NICKNAME_KEY));
        user.setPassword(MD5.create().digestHex(loginAccount.getPassword()));
        user.setStatus(1);
        user.setAvatar("https://b0.bdstatic.com/ac1b7570f5eb5527a99a0997179662a4.jpg@h_1280");
        userMapper.insert(user);
        userBillFeignClient.init(user.getId());
        return Result.ok();
    }
}
